<?php

namespace App\Kuafu\Dashboard\Controller\Merchant;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Common\Enum\CodeEnum;
use App\Kuafu\Dashboard\Service\DashboardService;
use App\Kuafu\Invoice\Service\InvoiceService;
use App\Kuafu\User\Enum\PermissionsEnum;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Kuafu\User\Model\UserRoleMapping;
use App\Kuafu\User\Service\AuthService;
use App\Library\FeiShu\SendFs;
use App\Library\KfHttp\TigerCurl;
use Illuminate\Http\Request;

class DashboardController extends BaseController
{

    /**
     * @param $request
     * @throws \App\Exceptions\BaseException
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public function permissionActions(Request $request)
    {
        $userId     = AuthService::getAuthUser()->id;
        $payload    = AuthService::getPayload()->toArray();
        $appVersion = $request->header('version', '');
        // 用户-职位权限
        $isStaff = isset($payload["thirdLoginType"]) && $payload["thirdLoginType"];
        if ($isStaff) {
            $menusList = DashboardService::getMenusV2([config('merchant.manager_role_id')],
                CodeEnum::PLATFORM_BUSINESS);
        } else {
            $roleList  = UserRoleMapping::getUserRoleList($userId, $this->brandId, $this->shopId,
                RoleCodeEnum::ROLE_BUSINESS_TYPE);
            $menusList = DashboardService::getMenusV2($roleList->pluck('roleId')->toArray(),
                CodeEnum::PLATFORM_BUSINESS);
        }

        $actions = [];
        foreach ($menusList as $v) {
            foreach ($v['children'] as $vv) {
                foreach ($vv['children'] as $vvv) {
                    foreach ($vvv['permissionList'] as $vvvv) {
                        $actions[] = $vvvv['action'];
                    }
                }
            }
        }
        $actions = array_unique($actions);

//        // 我的开店订单
//        if (in_array('app.my.openShopOrder', $actions)) {
//            $myOpenOrder = TigerCurl::getIns()
//                                    ->do('callback/appEntrance/' . $this->shopId, [],
//                                        'GET')['data']['myOpenOrder'] ?? false;
//        } else {
//            $myOpenOrder = false;
//        }
        // 纯用户权限, 与职位无关
        $buttonList = DashboardService::getMerchantButtonList($userId, $this->shopId);
        $actions    = array_merge($actions, $buttonList);


        //订货开票门店内测:后续可整块删除
        $invoiceShopAuth = InvoiceService::checkIsAllowInvoice($this->shopId);
        if (!empty($actions)) {
            foreach ($actions as $key => $act) {
                if (!$invoiceShopAuth && $act == "app.shop.tools.invoice") {
                    unset($actions[$key]);
                }
            }
        }

        // 客服中心展示
        $tigerData = TigerCurl::getIns()
            ->do('internal/user/getChatGroupIdByUser', ['userId' => $userId, 'shopId' => $this->shopId], 'GET')['data'] ?? [];
        if (isset($tigerData['groupId']) && $tigerData['groupId'] > 0) {
            $actions[] = 'app.my.chatGroup';
        }

        // 资质报告
        $qualificationReportPowerRes = DashboardService::qualificationReportPower($userId, $this->shopId);
        if ($qualificationReportPowerRes) {
            $actions[] = 'app.shop.tools.qualificationReport';
        }

        // 门店自检
        $shopCheckSelfPowerRes = DashboardService::shopCheckSelfPowerRes($userId, $this->shopId);
        if ($shopCheckSelfPowerRes) {
            $actions[] = 'app.shop.operatingServices'; // 添加默认权限
            $actions[] = 'app.shop.selfCheck';
        }

        $actions = array_values($actions);

        // 角标
        $actionStatus = DashboardService::getActionStatus($actions, $this->shopId);

        $data = [
            'actions'     => $actions,
            'actionsStatus' => $actionStatus,
            'myOpenOrder' => in_array('app.my.openShopOrder', $actions), // 历史问题需要兼容，开店订单icon展示入口
            'myServe'     => DashboardService::getMyServeByPower($userId, $this->shopId, $actions, $appVersion),  //我的服务
            'bottomList'  => [
                "intendedSiteSelection" => DashboardService::intendedSiteSelectionShowStatus($actions, $this->shopId)
            ]
        ];

        return $this->success($data);
    }


    /**
     * 获取底部按钮状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public function bottomButtonShow(Request $request): \Illuminate\Http\JsonResponse
    {
        $userId = AuthService::getAuthUser()->id;
        return $this->success(DashboardService::bottomButtonShow($userId, $request->header('shopId', 0)));
    }
}
